package com.example.sturedis.controller;

import com.alibaba.fastjson.JSON;
import com.example.sturedis.consts.StuRedisConst;
import com.example.sturedis.pojo.Student;
import com.example.sturedis.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//@RestController
//@RequestMapping("/stu")
@Slf4j
public class StudentController2 {

    @Autowired
    private StudentService studentService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/{id}")
    public Student findById(@PathVariable("id")Integer id){

        String key = StuRedisConst.STU_CACHE_PREFIX + id; //CACHE:STU:ID:2

        //先查询缓存
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(value)){
            //缓存没查到--查询数据库 + 存入缓存 + 返回数据
            log.info("缓存中没有数据，当前从数据库查询的id为：{}",id);
            Student stu = studentService.getById(id);
            if (stu != null){
                //存入缓存
                redisTemplate.opsForValue().set(key, JSON.toJSONString(stu));
            }else{
                /**
                 * 缓存穿透解决方式一：如果数据库没有查询到，我也向缓存中缓存一个空对象 -- 缓存空对象
                 * 问题：会向redis中存入大量无意义的数据
                 */
                redisTemplate.opsForValue().set(key, JSON.toJSONString(new Student()));
            }

            return stu;
        }

        log.info("命中缓存,当前查询的id为：{}",id);
        //缓存中有，返回数据
        Student stu = JSON.parseObject(value, Student.class);
        return stu;
    }
}
